<script lang="ts" setup>
import type { ComponentMeta } from '@/definitions/type'
import { useDesignStore } from '@/stores'
import { noop } from '@/utils/helper'
import { computed, defineAsyncComponent } from 'vue'
import { renderMap } from './renderMap'
import RenderTools from './RenderTools/RenderTools.vue'

defineOptions({
  name: 'Render',
})
const props = defineProps<{
  render: ComponentMeta
  renderIndex: number
}>()
const designStore = useDesignStore()
const isActive = computed(() => designStore.activeRender?.id === props.render.id)
const component = computed(() => defineAsyncComponent({
  loader: renderMap.get(props.render.definition.code!),
}))

function handleRenderActive() {
  if (isActive.value)
    return
  designStore.setActiveRender(props.render)
}
</script>

<template>
  <div
    class="render" :class="[designStore.config.platform, isActive ? 'active-render' : '']"
    @pointerdown="handleRenderActive"
  >
    <!-- id是必须的! 用于获取每个render-component html代码 -->
    <div :id="render.id">
      <component :is="component" :render="render" />
    </div>
    <!-- render mask: 用于防止点击穿透跳转 -->
    <div class="render-mask" @click.capture.stop="noop" />
    <!-- render tools -->
    <RenderTools v-if="isActive" :render-index="renderIndex" />
  </div>
</template>

<style lang="less" scoped>
.render {
  @apply relative cursor-move min-h-10 w-full;
}
.render.pc {
  min-height: 64px;
}
.active-render {
  border: 2px solid var(--app-color-primary);
}
.render-mask {
  z-index: var(--render-zindex-basic);
  @apply absolute top-0 left-0 right-0 bottom-0 box-border;
}
</style>
